import { defineStore } from 'pinia';
import { 
  submitAnswer, 
  getAnswerList, 
  likeAnswer, 
  likeQuestion,
  submitQuestion,
  getQuestionList,
  getQuestionDetail 
} from '../api/answer.js';

export const useAnswerStore = defineStore('answer', {
  state: () => ({
    // 问题列表
    questionList: [],
    // 回答列表
    answerList: [],
    // 加载状态
    loading: false,
    // 当前问题ID
    currentQuestionId: null,
    // 当前问题详情
    currentQuestion: null
  }),

  getters: {
    // 获取问题列表
    getQuestions: (state) => state.questionList,
    // 获取回答列表
    getAnswers: (state) => state.answerList,
    // 获取加载状态
    isLoading: (state) => state.loading,
    // 获取当前问题ID
    getCurrentQuestionId: (state) => state.currentQuestionId,
    // 获取当前问题详情
    getCurrentQuestion: (state) => state.currentQuestion
  },

  actions: {
    // 提交问题
    async submitNewQuestion(questionDTO) {
      try {
        this.loading = true;
        const res = await submitQuestion({
          content: questionDTO.content,
          detail: questionDTO.detail || '',
          fruitId: questionDTO.fruitId
        });
        if (res.code === 200) {
          // 提交成功后刷新问题列表
          await this.loadQuestionList({
            fruitId: questionDTO.fruitId,
            type: 0
          });
          return res.data;
        }
        return null;
      } catch (error) {
        console.error('提交问题失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 加载问题列表
    async loadQuestionList(queryDTO) {
      try {
        this.loading = true;
        const res = await getQuestionList({
          fruitId: queryDTO.fruitId,
          keyword: queryDTO.keyword || '',
          type: queryDTO.type || 0
        });
        if (res.code === 200) {
          this.questionList = res.data.map(question => ({
            ...question,
            isReplying: false // 添加UI状态
          }));
        }
        return res;
      } catch (error) {
        console.error('获取问题列表失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 加载问题详情
    async loadQuestionDetail(questionId) {
      try {
        this.loading = true;
        const res = await getQuestionDetail(questionId);
        if (res.code === 200) {
          this.currentQuestion = res.data;
          this.currentQuestionId = questionId;
        }
        return res;
      } catch (error) {
        console.error('获取问题详情失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 提交回答
    async submitNewAnswer(answerDTO) {
      try {
        this.loading = true;
        const res = await submitAnswer(answerDTO);
        if (res.code === 200) {
          // 提交成功后刷新回答列表
          if (this.currentQuestionId) {
            await this.loadAnswerList(this.currentQuestionId);
          }
          return res.data;
        }
        return null;
      } catch (error) {
        console.error('提交回答失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 加载回答列表
    async loadAnswerList(questionId) {
      try {
        this.loading = true;
        this.currentQuestionId = questionId;
        const res = await getAnswerList(questionId);
        if (res.code === 200) {
          this.answerList = res.data;
        }
        return res;
      } catch (error) {
        console.error('获取回答列表失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 点赞/取消点赞问题
    async toggleQuestionLike(questionId) {
      try {
        const res = await likeQuestion(questionId);
        if (res.code === 200) {
          // 更新本地问题的点赞状态
          const question = this.questionList.find(item => item.id === questionId);
          if (question) {
            question.isLiked = res.data;
            question.likeCount = question.isLiked ? 
              (question.likeCount || 0) + 1 : 
              Math.max((question.likeCount || 0) - 1, 0);
          }
          // 如果是当前问题，也更新当前问题的点赞状态
          if (this.currentQuestion && this.currentQuestion.id === questionId) {
            this.currentQuestion.isLiked = res.data;
            this.currentQuestion.likeCount = this.currentQuestion.isLiked ?
              (this.currentQuestion.likeCount || 0) + 1 :
              Math.max((this.currentQuestion.likeCount || 0) - 1, 0);
          }
          return res.data;
        }
        return false;
      } catch (error) {
        console.error('点赞问题失败:', error);
        throw error;
      }
    },

    // 点赞/取消点赞回答
    async toggleAnswerLike(answerId) {
      try {
        const res = await likeAnswer(answerId);
        if (res.code === 200) {
          // 更新本地回答的点赞状态
          const answer = this.answerList.find(item => item.id === answerId);
          if (answer) {
            answer.isLiked = res.data;
            answer.likeCount = answer.isLiked ? 
              (answer.likeCount || 0) + 1 : 
              Math.max((answer.likeCount || 0) - 1, 0);
          }
          return res.data;
        }
        return false;
      } catch (error) {
        console.error('点赞回答失败:', error);
        throw error;
      }
    },

    // 清空问题列表
    clearQuestionList() {
      this.questionList = [];
    },

    // 清空回答列表
    clearAnswerList() {
      this.answerList = [];
      this.currentQuestionId = null;
    },

    // 清空所有数据
    clearAll() {
      this.questionList = [];
      this.answerList = [];
      this.currentQuestionId = null;
      this.currentQuestion = null;
    }
  }
});
